import { FC, useEffect, useState } from 'react';
import MoneyInput from './MoneyInput';
import { RootState } from '../../store/store';
import { useSelector } from 'react-redux';

interface ExchangeRateData {
    [currency: string]: {
        [toCurrency: string]: number
    }
}

type CurrencyCode = 'USD' | 'EUR' | 'GBP' | 'JPY' | 'CNY';

const MoneyTransfer: FC = () => {
    const [fromCurrency, setFromCurrency] = useState<CurrencyCode>('USD');
    const [toCurrency, setToCurrency] = useState<CurrencyCode>('CNY');
    const [amount, setAmount] = useState<number>(1);
    const [rate, setRate] = useState<number>(0);
    const [convertedAmount, setConvertedAmount] = useState<number>(0);
    const [error, setError] = useState<string | null>(null);
    const [currencies, setCurrencies] = useState<CurrencyCode[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const todos = useSelector((state: RootState) => state.todos.items);

    const fetchCurrencyAndExchangeRate = async () => {
        try {
            const mockRates: ExchangeRateData = {
                USD: { CNY: 7.2, EUR: 0.92, GBP: 0.79, JPY: 145.8, USD: 1 },
                CNY: { USD: 0.14, EUR: 0.13, GBP: 0.11, JPY: 20.25, CNY: 1 },
                EUR: { USD: 1.09, CNY: 7.83, GBP: 0.86, JPY: 158.5, EUR: 1 },
                GBP: { USD: 1.27, CNY: 9.1, EUR: 1.16, JPY: 184.6, GBP: 1 },
                JPY: { USD: 0.0069, CNY: 0.049, EUR: 0.0063, GBP: 0.0054, JPY: 1 }
            };
            await new Promise(resolve => setTimeout(resolve, 500));

            if (mockRates[fromCurrency] && mockRates[fromCurrency][toCurrency]) {
                const rate = mockRates[fromCurrency][toCurrency];
                setRate(rate);
                setConvertedAmount(amount * rate);
                setCurrencies(Object.keys(mockRates) as CurrencyCode[]);
            } else {
                throw new Error('Rate is not available.');
            }
            setLoading(false);
        }
        catch (error) {
            if (error instanceof Error) {
                setError(error.message);
            } else {
                setError('An unknown error occurred.');
            }
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchCurrencyAndExchangeRate();
    }, [fromCurrency, toCurrency, amount,convertedAmount]);

    const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = parseFloat(e.target.value);
        if (!isNaN(value)) {
            setAmount(value);
        }
    };

    const handleFromCurrencyChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        console.log("🚀 ~ FROMFROMFROMFROMFROMFROMFROMFROMFROM:",);
        setFromCurrency(e.target.value as CurrencyCode);
    };

    const handleToCurrencyChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        console.log("🚀 ~ TOTOTOOTOTO:",);

        setToCurrency(e.target.value as CurrencyCode);
    };


    return (
        <div>
            {loading && <div>Loading...</div>}
            {error && <div>{error}</div>}

            {todos.map((todo) => <div>
                <p>Todo: {todo.text}</p>
            </div>)}

            {!loading && !error &&
                <>
                    <div>
                        <MoneyInput
                            type='FROM'
                            amount={amount}
                            fromCurrency={fromCurrency}
                            toCurrency={toCurrency}
                            currencies={currencies}
                            onAmountChange={handleAmountChange}
                            onFromCurrencyChange={handleFromCurrencyChange}
                        />

                    </div>

                    <div className="conversion-info">
                        <p>1 {fromCurrency} = {rate.toFixed(4)} {toCurrency}</p>
                        <i className="fa fa-exchange" aria-hidden="true"></i>
                    </div>

                    <div>
                        <MoneyInput type='TO' amount={convertedAmount}
                            fromCurrency={fromCurrency}
                            toCurrency={toCurrency}
                            currencies={currencies}
                            onToCurrencyChange={handleToCurrencyChange}

                        ></MoneyInput>
                    </div>
                </>
            }
        </div>
    );
};

export default MoneyTransfer;